#include "DistanceTransformAction.h"
#include <QImage>
#include <cmath>
#include "DistanceTransform.h"
#include "Layer.h"
#include "Work.h"
#include "FilterLinear.h"



DistanceTransformAction::DistanceTransformAction () : AbstractAction ()
{

}

void DistanceTransformAction::updatePreview (QRect viewport)
{
	Ptr< Layer > pCurLayer = __pTargetWork->getDoc ()->getCurrentLayer ();

	bool isPreview = true;
	if (viewport.isEmpty ()) {
		isPreview = false;
		viewport = pCurLayer->getRegion ();
	}

	QRect updateRegion = viewport & pCurLayer->getRegion ();

	QPoint oSrcImg = pCurLayer->getRegion ().topLeft ();
	QPoint oViewport = viewport.topLeft ();
	QPoint oUpdate = updateRegion.topLeft ();

	QRect processRegion = updateRegion;
	processRegion.translate (-oSrcImg);

	Ptr< QImage > pProcessSrc = new QImage (pCurLayer->getImage ()
			->copy (processRegion));

	Ptr< QImage > pProcessResult = DistanceTransform ()
			.process (pProcessSrc);

	if (isPreview)
		pCurLayer->setPreviewImage (pProcessResult);
	else
		pCurLayer->setImage (pProcessResult);

}

void DistanceTransformAction::handleStartEvent ()
{
	__pTargetWork->getDoc ()->getCurrentLayer ()->openPreview ();
}

void DistanceTransformAction::rejectAction ()
{
	__pTargetWork->getDoc ()->getCurrentLayer ()->closePreview ();
}

void DistanceTransformAction::applyAction ()
{
	updatePreview (QRect ());
	__pTargetWork->getDoc ()->getCurrentLayer ()->closePreview ();
}
